package top.jfunc.common.utils.local;

import org.slf4j.MDC;
import top.jfunc.common.utils.MapUtil;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 串联子线程和主线程的{@link MDC}数据
 */
public class MDCWrapperCallable<T> implements Callable<T> {

    private final Callable<T> callable;

    private final Map<String, String> map;

    public MDCWrapperCallable(Callable<T> callable) {
        this.callable = callable;
        // 保存当前线程的MDC值
        this.map = MDC.getCopyOfContextMap();
    }

    @Override
    public T call() throws Exception {
        if(!MapUtil.isEmpty(this.map)){
            this.map.forEach(MDC::put);
        }
        // 装饰器模式，执行run方法
        try {
            return callable.call();
        }finally {
            if(!MapUtil.isEmpty(map)){
                this.map.keySet().forEach(MDC::remove);
                this.map.clear();
            }
        }
    }
    
}